<template>
  <div class="ver-layout">
    <!--  表单  -->
    <el-form ref="formRef" :model="pageData.formData" inline size="small">
      <el-form-item label="姓名" class="form-item-view" prop="userName">
        <el-select v-model="pageData.formData.userName" filterable multiple clearable placeholder="请选择">
          <el-option v-for="(item,index) in pageData.userNameOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="员工编号" class="form-item-view" prop="userCode">
        <el-select v-model="pageData.formData.userCode" filterable multiple clearable placeholder="请选择">
          <el-option v-for="(item,index) in pageData.userCodeOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="考勤类型" class="form-item-view" prop="dayOffType">
        <el-select v-model="pageData.formData.dayOffType" filterable multiple clearable placeholder="请选择">
          <el-option v-for="(item,index) in pageData.dayOffTypeOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value"
                     :disabled="item.disabled"/>
        </el-select>
      </el-form-item>
      <div class="hor-layout-side-center"
           style="padding-bottom: 10px;margin-bottom: 20px;margin-right: 50px;border-bottom: 1px solid #909399">
        <div class="hor-layout">
          <el-button type="success" size="small" @click="uploadClick">上传请假表格</el-button>
          <el-button type="warning" size="small" :loading="pageData.tableDiffLoading" @click="compareDifferent">
            对比表格数据差异
          </el-button>
        </div>
        <div class="hor-layout">
          <el-button type="default" size="small" @click="resetFormData"
                     :disabled="pageData.tableByCheckLoading">
            重置
          </el-button>
          <el-button type="primary" size="small" @click="queryFormData"
                     :disabled="pageData.tableByCheckLoading">
            查询
          </el-button>
        </div>
      </div>
    </el-form>
    <!--  表格  -->
    <div class="hor-layout-center" style="margin-top: -10px;margin-bottom: 8px">
      <div v-if="haveOffTableData" class="title-flag-view" style="flex: 1;">上传的请假表格（表2）</div>
      <div class="hor-layout-center" style="flex: 1">
        <div class="title-flag-view flag-second">考勤表格生成的请假数据（表1—查询功能只对该表格生效）</div>
        <el-switch v-model="pageData.expandModel"
                   style="--el-switch-on-color: #13ce66; --el-switch-off-color: #f68080"
                   size="small"
                   inline-prompt
                   active-text="折叠模式"
                   inactive-text="非折叠模式"/>
      </div>
    </div>
    <div class="hor-layout" style="width: 100%">
      <!--   上传的请假表   -->
      <el-table v-if="haveOffTableData" ref="elTable2" :data="pageData.upOffTableData"
                width="50%" :height="topTableHeight" border size="small"
                v-loading="pageData.showUploadDialog" :cell-style="(data)=>cellStyle(data,1)"
                @cell-click="cellClick"
                @sort-change="sortChange($event,'2')">
        <el-table-column v-for="(headerItem,headerIndex) in pageData.upOffTableHeader"
                         :key="headerIndex"
                         :prop="headerItem"
                         :label="headerItem"
                         :sortable="headerItem=='员工编号'"
                         :width="getTableWidth(headerItem,2)"
                         :show-overflow-tooltip="true"/>
      </el-table>
      <div style="height: 100%;width:10px;visibility: hidden">divider</div>
      <!--   生成的请假表   -->
      <el-table v-if="true" ref="elTable1" :data="computedData.tableData"
                width="50%" :height="topTableHeight" border size="small"
                v-loading="pageData.tableByCheckLoading" :cell-style="(data)=>cellStyle(data,1)"
                row-key="id"
                :expand-row-keys="pageData.expandRowKeys"
                @cell-click="cellClick"
                @sort-change="sortChange($event,'1')">
        <el-table-column v-if="!pageData.expandModel" type="index" label="序号"></el-table-column>
        <el-table-column v-for="(headerItem,headerIndex) in computedData.tableHeader"
                         :key="headerIndex"
                         :prop="headerItem"
                         :label="headerItem"
                         :sortable="headerItem=='员工编号'"
                         :width="getTableWidth(headerItem)"
                         :show-overflow-tooltip="true"/>
      </el-table>
    </div>
    <div v-if="haveOffTableData" class="ver-layout">
      <div class="title-flag-view flag-third" style="margin-top: 15px;margin-bottom: 10px">
        请假表格差异数据（表1中的数据在表2中不存在，或者表1的请假时间大于表2的请假时间）
      </div>
      <el-table :data="pageData.diffTableList" width="50%" height="300px" border size="small"
                v-loading="pageData.tableDiffLoading"
                highlight-current-row
                :cell-style="(data)=>cellStyle(data,2)"
                @cell-click="cellClick"
                @current-change="diffTableCurrentChange">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column v-for="(headerItem,headerIndex) in pageData.diffTableHeader"
                         :key="headerIndex"
                         :prop="headerItem"
                         :label="headerItem"
                         :show-overflow-tooltip="true"/>
      </el-table>
    </div>
  </div>
  <!-- 上传弹窗 -->
  <el-dialog v-model="pageData.showUploadDialog" title="上传请假表格" center size="small" width="40%">
    <div class="ver-layout-center" style="width: 80%;margin:auto;padding: 30px">
      <el-form :model="pageData.uploadFormData" inline size="small">
        <el-form-item label="请假表所在sheet页序号" class="form-item-view1">
          <el-input type="number" v-model="pageData.uploadFormData.sheetIndex"/>
        </el-form-item>
      </el-form>
      <el-upload
          ref="uploadRef"
          class="upload-demo"
          accept=".xlsx,.xls"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :auto-upload="true"
          :before-upload="beforeUpload"
      >
        <template #trigger>
          <el-button type="primary" size="small">上传请假表</el-button>
        </template>
      </el-upload>
    </div>
  </el-dialog>
  <!--  个人月度考勤  -->
  <el-dialog v-model="pageData.showUserDayCheckDialog"
             draggable center size="small" width="50%">
    <dayCheckTableView :dialog-model="true" :selectDayData="pageData.selectDayData"/>
  </el-dialog>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref, watch} from "vue";
import type {FormInstance} from "element-plus";
import {dayOffType} from "@/utils/data_utils.ts";
import {
  compareDateSpanFn,
  formatDate,
  getDayOffData,
  getDevMode,
  readExcelFileWithMixCol,
  showLoading,
  showToast
} from "@/utils/utils.ts";
import {dayOffDemoData} from "@/utils/demo_data.ts";
import dayCheckTableView from "@/views/attendance/components/dayCheckTableView.vue";

interface Props {
  parentPageData?: Object;//
}

const props = withDefaults(defineProps<Props>(), {});

const formRef = ref<FormInstance>();
const elTable1 = ref<null>();
const elTable2 = ref<null>();

const pageData = reactive({
  // 差异表格加载标志
  tableDiffLoading: false,
  // 考勤表格生成的请假数据加载标志
  tableByCheckLoading: false,
  expandModel: false,
  expandRowKeys: [],
  //查询条件对象
  filterData: {},
  formData: {
    userName: [],
    userCode: [],
    dayOffType: [],
  },
  userNameOptions: [],
  userCodeOptions: [],
  dayOffTypeOptions: Object.keys(dayOffType).map(item => {
    return {
      label: item,
      value: item,
      disabled: false
    }
  }),
  //上传弹窗
  showUploadDialog: false,
  loadingView: '',
  uploadFormData: {
    sheetIndex: 0
  },
  //上传的请假表格
  upOffTableHeader: [],
  upOffTableData: [],
  //生成的差异表格
  diffTableHeader: ['员工姓名', '员工编号', '请假类型', '请假天数', '开始时间', '结束时间'],
  diffTableList: [],
  selDiffTableItem: "",//选中的差异数据表格里面的行
  sortOffDataByCheckTable: [],//排序后的——考勤表格生成的请假数据
  sortOffDataByOffTable: [],//排序后的——上传的请假表格
  //个人月考勤弹窗
  showUserDayCheckDialog: false,
  selectDayData: {}
})

//
const haveFilterData = computed(() => {
  return Object.values(pageData.filterData).filter(item => item && item.length).length
})

//存在上传的请假表格数据
const haveOffTableData = computed(() => {
  return pageData.upOffTableData.length
})

//上边的表格的高度
const topTableHeight = computed(() => {
  return haveOffTableData.value ? '230px' : '450px'
})

//表格生成的请假表格数据
const computedData = computed(() => {
  let {userName, userCode, dayOffType} = pageData.filterData
  let userNameStr = userName && userName.join(',')
  let userCodeStr = userCode && userCode.join(',')
  let dayOffTypeStr = dayOffType && dayOffType.join(',')
  let tableData = JSON.parse(JSON.stringify(props.parentPageData.tableData))
  // console.log("computedData==", tableData, userNameStr, userCodeStr, dayOffTypeStr)
  let filterTableData1 = tableData.filter(tableItem => {
    let tableItemValueList = Object.values(tableItem)
    let userNameFilter = userNameStr ? tableItemValueList.find(tableItemValue => userNameStr.includes(tableItemValue)) : true
    let userCodeFilter = userCodeStr ? tableItemValueList.find(tableItemValue => userCodeStr.includes(tableItemValue)) : true
    let dayOffTypeFilter = dayOffTypeStr ? tableItemValueList.find(tableItemValue => dayOffTypeStr.includes(tableItemValue)) : true
    return userNameFilter && userCodeFilter && dayOffTypeFilter
  })
  // console.log("computedData==filterTableData1", filterTableData1)
  let filterTableData3 = []
  if (Object.values(pageData.filterData).filter(item => item && item.length).length) {
    let filterTableData2 = filterTableData1.map((tableItem, tableItemIndex) => {
      Object.keys(tableItem).forEach((tableItemKey, index) => {
        // tableItem.id=`${tableItemIndex}_${index}`
        //1日 | 1日_1
        if (tableItemKey.includes('日') && !tableItemKey.includes("_")) {
          let allTableItem = tableData.find(allTableItem => allTableItem['员工编号'] == tableItem['员工编号'])
          if (['上午', '下午'].includes(tableItem[`${tableItemKey}_1`])) {
            tableItem[tableItemKey] = `${tableItem[tableItemKey]}/${tableItem[`${tableItemKey}_1`]}`
          }
        }
        let tableItemDayOff = tableItem[tableItemKey].includes("/") ? tableItem[tableItemKey].split("/")[0] : tableItem[tableItemKey]
        if (tableItemKey.includes('日') && dayOffTypeStr && !dayOffTypeStr.includes(tableItemDayOff)) {
          tableItem[tableItemKey] = ''
        }
      })
      return tableItem
    })
    // console.log("computedData==filterTableData2", filterTableData2)
    filterTableData2.forEach((tableItem, tableItemIndex) => {
      let filterTableItemKeys = Object.keys(tableItem).filter(tableItemKey => tableItemKey.includes("日") && tableItem[tableItemKey]).map(item => parseInt(item.replace("日", "")))
      let dayOffData = getDayOffData(filterTableItemKeys, tableItem, tableItemIndex)
      let dayOffDataList = Object.values(dayOffData)
      if (pageData.expandModel) {
        filterTableData3.push({
          "id": tableItem['员工编号'],
          "序号": tableItemIndex + 1,
          "员工姓名": tableItem['员工姓名'],
          "员工编号": tableItem['员工编号'],
          "请假类型": dayOffDataList.map(item => item['请假类型']).reduce((total, value) => {
            !total.includes(value) && total.push(value)
            return total
          }, []).join(","),
          "请假天数": dayOffDataList.map(item => item['请假天数']).reduce((total, value) => total + value),
          "children": dayOffDataList
        })
      } else {
        filterTableData3.push(...dayOffDataList)
      }
    })
  }
  // console.log("computedData==filterTableData3", filterTableData3)
  let tableHeader = ["序号", "子序号", "员工姓名", "员工编号", "请假类型", "请假天数", "开始时间", "结束时间"]
  if (!pageData.expandModel) {
    tableHeader.splice(0, 2)
  }
  return {
    tableData: haveFilterData ? filterTableData3 : filterTableData1,
    tableHeader: tableHeader,
  }
})

const cellStyle = (data, type) => {
  // console.log("cellStyle==", data)
  //和选中的员工编号一直的行
  let isSelUserRow = type == 1 && data.row['员工编号'] == (pageData.selDiffTableItem && pageData.selDiffTableItem['员工编号'])
  //员工姓名列
  let userNameCol = data.columnIndex == 1
  return {
    color: userNameCol ? 'blue' : '',
    textDecoration: userNameCol ? 'underline' : '',
    backgroundColor: isSelUserRow ? '#ffb9b9' : ''
  }
}

const cellClick = (row, column) => {
  console.log("cellClick", row, column)
  //row：序号:2 id:80030698
  //column：no:0
  if (column.label == '员工姓名') {
    let tableData = JSON.parse(JSON.stringify(props.parentPageData.tableData))
    pageData.showUserDayCheckDialog = true
    let selectDayData = tableData.find(item => item['员工编号'] == row['员工编号'])
    Object.keys(selectDayData).forEach(selectDayItemKey => {
      if (selectDayItemKey.includes('日') && !selectDayItemKey.includes("_")) {
        if (['上午', '下午'].includes(selectDayData[`${selectDayItemKey}_1`])) {
          selectDayData[selectDayItemKey] = `${selectDayData[selectDayItemKey]}/${selectDayData[`${selectDayItemKey}_1`]}`
        }
      }
    })
    pageData.selectDayData = selectDayData
  }
}

//排序改变
const sortChange = (data, type) => {
  console.log("sortChange==", data)
  const sortMethod = (a, b) => {
    if (data.order == 'ascending') return a[data.prop] - b[data.prop]
    if (data.order == 'descending') return b[data.prop] - a[data.prop]
    return a[data['序号']] - b[data['序号']]
  }
  if (type == 1) pageData.sortOffDataByCheckTable = JSON.parse(JSON.stringify(computedData.value.tableData)).sort(sortMethod)
  if (type == 2) pageData.sortOffDataByOffTable = JSON.parse(JSON.stringify(pageData.upOffTableData)).sort(sortMethod)
  // console.log("sortChange==", pageData.sortOffDataByCheckTable)
}

//差异表格选中事件
const diffTableCurrentChange = (currentRow) => {
  pageData.selDiffTableItem = currentRow
  let tableIndex1 = pageData.sortOffDataByCheckTable.findIndex(item => item['员工编号'] == currentRow['员工编号'])
  let tableIndex2 = pageData.sortOffDataByOffTable.findIndex(item => item['员工编号'] == currentRow['员工编号'])
  let rowHeight = 32
  // console.log("tableIndex", tableIndex1, rowHeight)
  elTable1.value.scrollTo(0, tableIndex1 * rowHeight)
  elTable2.value.scrollTo(0, tableIndex2 * rowHeight)
  // elTable1.value.setCurrentRow(computedData.value.tableData[tableIndex1])
  // elTable2.value.setCurrentRow(pageData.upOffTableData[tableIndex2])
}

//获取单元格宽度
const getTableWidth = (headerItem, tableFlag = 1) => {
  if (!haveOffTableData.value) return ""
  if (['序号'].includes(headerItem)) return '60px'
  if (['子序号', "总天数"].includes(headerItem)) return '60px'
  // if (['请假天数'].includes(headerItem)) return '70px'
  if (['开始时间', '结束时间', '开始日期', '结束日期'].includes(headerItem)) return '145px'
  if (['员工姓名'].includes(headerItem) && tableFlag == 2) return '100px'
  if (['员工编号'].includes(headerItem)) return '90px'
}

//对比差异
const compareDifferent = () => {
  if (!computedData.value.tableData.length) {
    showToast("请上传考勤表格！", "warning")
    return
  }
  if (!pageData.upOffTableData.length) {
    showToast("请上传请假表格！", "warning")
    return
  }
  pageData.tableDiffLoading = true
  setTimeout(() => {
    let diffTableList = computedData.value.tableData.filter(checkTableItem => {
      let offTableFilterList = pageData.upOffTableData.filter(offTableItem => checkTableItem['员工编号'] == offTableItem['员工编号'] && compareDateSpanFn(checkTableItem, offTableItem))
      return !offTableFilterList.length
    })
    diffTableList.sort((a, b) => a['员工编号'] - b['员工编号'])
    pageData.diffTableList = JSON.parse(JSON.stringify(diffTableList))
    //按员工编号升序排序
    elTable1.value.sort('员工编号', 'ascending')
    elTable2.value.sort('员工编号', 'ascending')
    pageData.tableDiffLoading = false
  }, 300)
}

const uploadClick = () => {
  pageData.uploadFormData.sheetIndex = 0
  pageData.showUploadDialog = true;
}

//上传之前
const beforeUpload = async (file) => {
  console.log("beforeUpload==", file)
  pageData.loadingView = showLoading();
  let tableData = await readExcelFileWithMixCol(file, pageData.uploadFormData.sheetIndex)
  initUpOffTableData(tableData)
  pageData.loadingView.close()
  pageData.loadingView = null
  pageData.showUploadDialog = false;
  // compareDifferent()
  // console.log("pageData==", JSON.stringify(pageData))
}

//初始化表格数据
const initUpOffTableData = (tableData) => {
  let tableHeader = tableData && tableData.length && tableData[0]
  let filterHeader = ['序号', '员工姓名', '员工编号', '请假类型', '总天数', '开始日期', '结束日期', '请假天数', '公休假天数', '法定假天数', '工时类型', '状态']
  pageData.upOffTableHeader = filterHeader || Object.keys(tableHeader)
  pageData.upOffTableData = tableData.map(tableItem => {
    // console.log("typeof tableItem", typeof tableItem['开始日期'])
    // if (typeof tableItem['开始日期'] === "number") tableItem['开始日期'] = formatExcelDate(tableItem['开始日期'])
    // if (typeof tableItem['结束日期'] === "number") tableItem['结束日期'] = formatExcelDate(tableItem['结束日期'])
    if (typeof tableItem['开始日期'] === "object") tableItem['开始日期'] = formatDate(tableItem['开始日期'])
    if (typeof tableItem['结束日期'] === "object") tableItem['结束日期'] = formatDate(tableItem['结束日期'])
    return tableItem
  })
  // console.log("pageData.upOffTableHeader", pageData.upOffTableHeader)
  // console.log("pageData.upOffTableData", pageData.upOffTableData)
}

const resetFormData = () => {
  formRef.value?.resetFields()
  queryFormData()
}

const queryFormData = () => {
  pageData.tableByCheckLoading = true
  setTimeout(() => {
    pageData.filterData = JSON.parse(JSON.stringify(pageData.formData))
    pageData.tableByCheckLoading = false
  }, 300)
  // console.log("queryFormData", JSON.stringify(props.parentPageData.tableData))
}

//监听
watch(props.parentPageData, (data) => {
  pageData.userNameOptions = data.tableData.map(tableItem => {
    return {
      label: tableItem['员工姓名'],
      value: tableItem['员工姓名']
    }
  })
  pageData.userCodeOptions = data.tableData.map(tableItem => {
    return {
      label: tableItem['员工编号'],
      value: tableItem['员工编号']
    }
  })
  //更新考勤类型里面的可选属性
  let totalSeries = {}
  data.tableHeader.filter(item => item.includes("日")).forEach(dayName => {
    data.tableData.forEach(userItem => {
      let dayOff = userItem[dayName]
      totalSeries[dayOff] = dayOff
    })
  })
  let totalSeriesKeys = Object.keys(totalSeries)
  // console.log("totalSeriesKeys==", data.tableHeader, totalSeries, totalSeriesKeys)
  pageData.dayOffTypeOptions = pageData.dayOffTypeOptions.map(item => {
    item.disabled = !totalSeriesKeys.includes(item.value)
    return item
  })
  pageData.dayOffTypeOptions.sort((a, b) => a.disabled - b.disabled)
  setTimeout(() => {
    let filterNotList = ['出勤', '双休日', '公出']
    pageData.formData.dayOffType = pageData.dayOffTypeOptions.filter(item => !item.disabled && !filterNotList.includes(item.value)).map(item => item.value)
    queryFormData()
  })
  // console.log("pageData.dayOffTypeOptions==", JSON.stringify(pageData.dayOffTypeOptions))
}, {
  immediate: true,
})

onMounted(() => {
  if (getDevMode() == 'development') initUpOffTableData(dayOffDemoData.offTableData)
})
</script>

<style scoped>
.form-item-view {
  width: 30%;
}

.title-flag-view {
  height: 20px;
  line-height: 20px;
  padding-left: 10px;
  margin-right: 10px;
  font-weight: bold;
  font-size: 14px;
  border-left: 8px solid #a0da0d;
}

.flag-second {
  border-left: 8px solid #409eff;
}

.flag-third {
  border-left: 8px solid #e6a23c;
}

/deep/ .el-table .current-row > td {
  background-color: #10aedd !important; /* 自定义颜色 */
}
</style>